package audioPlayer;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import objects.Track;
import objects.TrackLine;

import drawables.Drawable;
import drawables.DrawableManager;
import java.util.HashMap;
import java.util.List;
import javafx.scene.media.Media;

public class AudioPlayer {
	// ----- singletone. -----
	static AudioPlayer ap=new AudioPlayer();
	public static final int QUANT_MIN = 1;
	public static final int QUANT_MAX = 100;
	public static final int QUANT_INIT = 20;
        private int bpm=120;
	private AudioPlayer(){
            
	}
	
	static public AudioPlayer get(){
		return ap;
	}
	// -----------------------
	
	private Timer timer=null;
	private int quantizedMesurment=10;
	
        
        
        
        
        
        
	public int getBPM(){
		return bpm;
	}
	
        public void setBPM(int bpm){
            this.bpm = bpm;
        }
        
	public long getQuantizedTime(){
            long res;
            res = (long)(60000 / getBPM());
            return res;
	}
        
        public double getQuantizedTime2(){
            double res;
            res = (long)(((float)getBPM() / (float)120) * 1000);
            return res;
	}
	
	public int getQuantizedMesurment(){
		return quantizedMesurment;
	}
	
	public void setQuantizedMesurment(int quantizedMesurment) {
		this.quantizedMesurment = quantizedMesurment;
	}
	
	public int timeToMesurment(double time){
		return (int)(((time * 1000) / (double)getQuantizedTime()) * getQuantizedMesurment());
	}
	
	public void play(List<Track> tracks){
		DrawableManager.get().getTrackLine().reset();
		stop(tracks);
		timer = new Timer();
		for(Track t : tracks){
			t.play();
		}
		
		timer.scheduleAtFixedRate(new TimerTask() {
			
			@Override
			public void run() {
				TrackLine tl = DrawableManager.get().getTrackLine();
				tl.setX(tl.getX()+1);
			}
		}, 0, getQuantizedTime() / getQuantizedMesurment());
	}
	
	public void stop(List<Track> tracks){
		for(Track t : tracks){
			t.stop();
		}
		if(timer!=null)
			timer.cancel();
		DrawableManager.get().getTrackLine().reset();
	}
}
